//class made by Teo ( www.teodorfilimon.com ). More about the app in readme.txt

package com.teo.tools.counter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.teo.tools.counter.Counter.CounterState;

/**
 * This class handles all the interactions with the DB.
 */
public class DB {

	// total time passed since the beginning to current event
	public static final String KEY_TIME = "time";
	// total time passed since previous event to current event
	public static final String KEY_GAP = "gap";
	// value of counter after current event
	public static final String KEY_VALUE = "value";

	private static final String DB_NAME = "data";
	private static final String DB_STATS_TABLE = "stats";
	private static final int DB_VERSION = 5;
	private static Context mContext;
	private SQLiteDatabase mDb;
	private DatabaseHelper mDbHelper;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + DB_STATS_TABLE + " (" + KEY_TIME
					+ " integer, " + KEY_GAP + " integer, " + KEY_VALUE
					+ " integer);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {			
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public DB(Context c) {
		mContext = c;
	}

	/**
	 * Open the database. If it cannot be opened, try to create a new instance
	 * of the database. If it cannot be created, throw an exception to signal
	 * the failure.
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public DB open() throws SQLException {
		mDbHelper = new DatabaseHelper(mContext);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Exports a CVS with the stats on the SD card
	 * 
	 * @return the path if the export succeeds, null if it fails
	 */
	public String exportToCSV() {
		Cursor c = getCursor();

		if (c.getCount() == 0) {
			return null;
		}

		int time = c.getColumnIndex(KEY_TIME);
		int gap = c.getColumnIndex(KEY_GAP);
		int value = c.getColumnIndex(KEY_VALUE);

		Date d = new Date();
		String path = null;
		try {
			File f = new File("/sdcard/Time-Counter/");
			if (f.exists() == false) {
				f.mkdirs();
			}
			FileOutputStream out = new FileOutputStream(new File(
					(path = "/sdcard/Time-Counter/" + d.getDate() + '-'
							+ d.getMonth() + '-' + (d.getYear() + 1900) + "_"
							+ d.getHours() + '-' + d.getMinutes() + '-'
							+ d.getSeconds() + ".csv")));
			c.moveToFirst();
			do {
				out.write((c.getLong(time) + "," + c.getLong(gap) + ","
						+ c.getLong(value) + '\n').getBytes());
			} while (c.moveToNext());
			out.close();
		} catch (Exception e) {
		  c.close();
			return null;
		}
		c.close();
		return path;
	}

	public Cursor getCursor(){
		return mDb.query(DB_STATS_TABLE, new String[] { KEY_TIME, KEY_GAP,
				KEY_VALUE }, null, null, null, null, null);
	}
	
	/**
	 * Inserts a new counter event
	 * 
	 * @param cs
	 *            - the resulted counter state
	 */
	public void insert(CounterState cs) {
		ContentValues args = new ContentValues();
		args.put(KEY_TIME, cs.totalMillis);
		args.put(KEY_GAP, cs.millis);
		args.put(KEY_VALUE, cs.count);
		mDb.insert(DB_STATS_TABLE, null, args);
	}

	/**
	 * Deletes all the records in the DB
	 */
	public void reset() {
		mDb.delete(DB_STATS_TABLE, null, null);
	}

}
